package com.dtborad.myblog.common;

import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@Component
@Slf4j
public class AIChatUtil {
    public String getAIResponse(String content) throws Exception {
        StringBuilder fullResponse = new StringBuilder();
        try {
            //星火大模型AI调用
            String url = "https://spark-api-open.xf-yun.com/v1/chat/completions";
            String apiPassword = "EYfZfCHnBNDdTjTqLiRe:UlnyEeVUUjdmHeMkrLsA";
            // 动态构建请求体
            String requestBody = "{\"model\":\"lite\"," +
                    "\"messages\":[{\"role\":\"user\",\"content\":\"" + content + "\"}]," +
                    "\"stream\":true}";

            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Authorization", "Bearer " + apiPassword);
            con.setRequestProperty("Content-Type", "application/json");
            con.setDoOutput(true);

            try (OutputStream os = con.getOutputStream()) {
                os.write(requestBody.getBytes("UTF-8"));
            }

            int responseCode = con.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            if (responseCode == 200) {
                try (BufferedReader in = new BufferedReader(
                        new InputStreamReader(con.getInputStream()))) {
                    String line;
                    while ((line = in.readLine()) != null) {
                        if (line.startsWith("data: ")) {
                            String data = line.substring(6);
                            if (!data.equals("[DONE]")) {
                                JSONObject json = new JSONObject(data);
                                JSONObject choices = json.getJSONArray("choices").getJSONObject(0);
                                JSONObject delta = choices.getJSONObject("delta");
                                if (delta.has("content")) {
                                    fullResponse.append(delta.getString("content"));
                                }
                            }
                        }
                    }
                }
                //System.out.println("完整回复: " + fullResponse.toString());
            } else {
                try (BufferedReader errorReader = new BufferedReader(
                        new InputStreamReader(con.getErrorStream()))) {
                    String errorResponse = errorReader.lines().collect(java.util.stream.Collectors.joining());
                    System.err.println("API Error: " + errorResponse);
                    return errorResponse;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fullResponse.toString();
    }
}
